<template>
  <view class="container">
    <ve-card :title="record.feeName" type="none" fold>
      <template #status>
        <view class="status-2" v-if="record.feeTypeName">{{ record.feeTypeName }}</view>
        <view class="status-1" v-if="record.costTypeName">{{ record.costTypeName }}</view>
      </template>
      <ve-cell-price :label="costType == 0 ? '应收金额' : '应付金额'" :value="Math.abs(record.receiveAmount)"></ve-cell-price>
      <ve-cell-price :label="costType == 0 ? '待收金额' : '待付金额'" :value="Math.abs(record.receivedNotAmount)"></ve-cell-price>

      <block v-if="feeCategory == 1">
        <ve-cell-val label="保养单号" :value="record.businesCode" />
        <ve-cell-val label="修理厂" :value="record.supplierName" />
        <ve-cell-val label="车牌号" :value="record.carLicenseNo" />
        <ve-cell-val label="保养日期" :value="record.startTime" formate="date" />
        <ve-cell-val label="费用备注" :value="record.feeRemark" />
      </block>
      <block v-if="feeCategory == 2">
        <ve-cell-val label="维修单号" :value="record.businesCode" />
        <ve-cell-val label="修理厂" :value="record.supplierName" />
        <ve-cell-val label="车牌号" :value="record.carLicenseNo" />
        <ve-cell label="维修周期">{{ record.startTime }} - {{ record.endTime }}</ve-cell>
        <ve-cell label="">
          <text class="c3 fs30 fw400">时长：{{ record.rentDays || '-' }}</text>
        </ve-cell>
      </block>
      <block v-if="feeCategory == 3">
        <ve-cell-val label="年检单号" :value="record.businesCode" />
        <ve-cell-val label="年检厂" :value="record.supplierName" />
        <ve-cell-val label="车牌号" :value="record.carLicenseNo" />
        <ve-cell-val label="保养日期" :value="record.startTime" formate="date" />
        <ve-cell-val label="费用备注" :value="record.feeRemark" />
      </block>
      <block v-if="feeCategory == 4">
        <ve-cell-val label="违章单号" :value="record.businesCode" />
        <ve-cell-val label="车牌号" :value="record.violation.licenseNo" />
        <ve-cell-val label="违章时间" :value="record.violation.eventTime" />
        <ve-cell-val label="违章城市" :value="record.violation.eventCityName" />
        <ve-cell-val label="罚分" :value="record.violation.eventScore" unit="分" />
        <ve-cell-val label="处理方" :value="record.violation.handleTypeName" />
      </block>

      <!-- 表格 -->
      <FeeTable :record="record" v-if="['2', '4'].includes(feeCategory)"></FeeTable>
      <ve-gap size="24"></ve-gap>
    </ve-card>
    <!-- 表单 -->
    <ve-form ref="veFormRef" :model="form" :rules="rules">
      <ve-card type="none" fold v-model:initFold="foldStatus.fold1">
        <ve-form-item :label="costType == 0 ? '收款金额' : '付款金额'" unit="元" required>
          <ve-input-number v-model="form.actualAmount" :precision="2" disabled />
        </ve-form-item>
        <ve-form-item
          :label="costType == 0 ? '收款方式' : '付款方式'"
          required
          prop="paymentWay"
          labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
        >
          <ve-picker-inline
            v-model="form.paymentWay"
            placeholder="请选择"
            :range="paywayEnum"
            unit="arrowRight"
            @change="typeChange"
          ></ve-picker-inline>
        </ve-form-item>
        <ve-form-item
          v-if="form.paymentWay == 4"
          label="选择使用哪笔订单押金"
          labelPosition="top"
          labelTooltipContent="支持选择同一承租人下的芝麻免押押金、违章关联订单如果是线下支付的押金，使用其违章押金抵扣；芝麻免押使用的是租车押金&违章押金；芝麻免押的押金支持查看详情"
          required
          labelTooltipPosition="top"
          prop="deductionOrderId"
        >
          <view style="width: 100%">
            <remote-select
              slotStatus
              type="deductionOrder"
              v-model="form.deductionOrderId"
              placeholder="请选择"
              :outData="deductionOrderList"
              unit="arrowRight"
              @change="deductionOrderChange"
            >
              <template #remote-select>
                <view class="deduction-order-select">
                  <view style="width: 100%; display: flex; align-items: center; margin-bottom: 8rpx">
                    <text v-if="form.orderNo">{{ form.orderNo }}</text>
                    <text v-else class="placeholder">请选择订单</text>
                    <view class="remote-select_arrow">
                      <ve-icon name="arrow_right_0" size="32" :block="true" />
                    </view>
                  </view>
                  <text class="deduction-order-select-amount">{{ form.availableAmount }}</text>
                </view>
              </template>
            </remote-select>
            <ve-button
              v-if="form.deductionOrderId && form.payType == 4"
              type="plain"
              size="mini"
              :customStyle="{ backgroundColor: '#F3F7FF' }"
              style="width: 100%; margin-top: 24rpx"
              @click="toDeductionOrderDetail"
            >
              查看押金详情
            </ve-button>
          </view>
        </ve-form-item>
        <ve-form-item v-if="form.paymentWay == -1" label="结算主体" required prop="account">
          <ve-picker-inline v-model="form.account" placeholder="请选择" :range="accountList" unit="arrowRight" />
        </ve-form-item>
        <ve-form-item
          v-else
          :label="costType == 0 ? '收款账号' : '付款账号'"
          labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。"
        >
          <ve-picker-inline v-model="form.account" placeholder="请选择" :range="accountList" unit="arrowRight" />
        </ve-form-item>
        <ve-form-item
          v-if="form.paymentWay && form.paymentWay != -1"
          :label="costType == 0 ? '收款时间' : '付款时间'"
          required
          prop="paymentTime"
        >
          <ve-date-picker v-model="form.paymentTime" title="时间"></ve-date-picker>
        </ve-form-item>
        <ve-form-item label="客户名称" required prop="customerName" v-if="feeCategory == 4">
          <ve-input v-model="form.customerName" placeholder="请输入" :maxlength="20" />
        </ve-form-item>
        <ve-form-item label="客户名称" required prop="customerName" v-else>
          <remote-select
            v-if="feeCategory == 1"
            type="supplierMain"
            :label="form.customerName"
            v-model="form.customerId"
            @change="customerChange"
          />
          <remote-select
            v-if="feeCategory == 2"
            type="supplierRepair"
            :label="form.customerName"
            v-model="form.customerId"
            @change="customerChange"
          />
          <remote-select
            v-if="feeCategory == 3"
            type="supplierInspects"
            :label="form.customerName"
            v-model="form.customerId"
            @change="customerChange"
          />
        </ve-form-item>
        <ve-form-item :label="costType == 0 ? '客户付款账号' : '客户收款账号'">
          <ve-input v-model="form.customerAccount" placeholder="请输入" :maxlength="20" />
        </ve-form-item>
        <ve-form-item label="结算备注" :borderBottom="false" labelPosition="top">
          <ve-input type="textarea" v-model="form.settlementRemark" placeholder="请输入备注" :maxlength="200" />
        </ve-form-item>
      </ve-card>
    </ve-form>
    <ve-gap size="120"></ve-gap>

    <ve-bottom-box>
      <view class="bottom-btns">
        <view class="amount">
          {{ costType == 0 ? '收款金额' : '付款金额' }}：
          <text class="amount-num">{{ form.actualAmount }} </text>
          <text class="amount-pic">元</text>
        </view>
        <view class="line"></view>
        <ve-button type="primary" @click="toConfirm" :loading="okLoading" size="long">确认</ve-button>
      </view>
    </ve-bottom-box>
  </view>
</template>

<script setup>
  import FeeTable from './components/fee-table.vue'

  import { ref, computed } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import {
    getConfirmAssetFeeDetail,
    confirmAssetFee,
    violationToConfirmFee,
    violationConfirmFee,
    getDepositOrderList,
  } from '@/api/asset/asset-fee'
  import { getAccountByPageData, getAccountByWayAndType } from '@/api/dict/detail'
  import useFormFold from '@/hooks/useFormFold'
  import useToast from '@/hooks/useToast'
  import { getDepositType } from '@/api/order/sOrder'
  import { getDepositWay } from '@/api/order/lOrder'
  import { userStore } from '@/stores'

  const userInfoStore = userStore()
  const accountList = ref([])
  const feeRecordId = ref()
  /**
   * 1保养 2维修 3年检 4违章
   */
  const feeCategory = ref(null)
  const orderId = ref()
  const orderType = ref()
  const feeNameId = ref()
  const veFormRef = ref(null)
  const form = ref({})
  const rules = ref({
    paymentTime: {
      required: true,
      message: '请选择',
    },
    paymentWay: {
      required: true,
      message: '请选择',
    },
    actualAmount: {
      required: true,
      message: '请输入',
    },
    customerName: {
      required: true,
      message: '请输入',
    },
  })
  const okLoading = ref(false)
  const form_data = ref({})
  const record = ref({
    violation: {},
  })
  const feeDetailList = ref([])
  const costType = ref(null)
  const { foldStatus, foldValidate } = useFormFold([
    {
      key: 'fold1',
      props: ['paymentTime', 'paymentWay', 'customerName', 'account', 'deductionOrderId'],
    },
  ])

  const violationdata = ref()
  const getDetail = async (id) => {
    var res
    if (feeCategory.value == 4) {
      res = await violationToConfirmFee({ idList: [id] })
      violationdata.value = res.result.carAssetFeeList || []
    } else {
      res = await getConfirmAssetFeeDetail({ idList: [id] })
    }
    const result = res.result
    const { receiveAmount, receivedNotAmount, carAssetFeeList } = result

    record.value = {
      receiveAmount: receiveAmount,
      receivedNotAmount: receivedNotAmount,
      ...carAssetFeeList[0],
    }

    const violation = record.value.violation

    feeDetailList.value = carAssetFeeList[0]?.feeDetailList
    // console.log('feeDetailList.value', feeDetailList.value)
    form.value = {
      actualAmount: record.value.receivedNotAmount,
      customerId: record.value.supplierId,
      // 5.9.1.1 长短租关联订单确认费用并且是会员显示承租人名称
      customerName: violation?.orderId && violation?.memberId ? violation?.memberName : record.value.supplierName,
    }
    form.value.paymentTime = feeDetailList.value[0]?.createTime //默认时间
    costType.value = result.costType
    if (costType.value == 0) {
      form.value.actualAmount = Math.abs(res.result.receiveAmount) //固定金额，不可修改
    } else {
      form.value.actualAmount = Math.abs(res.result.receivedNotAmount) //固定金额，不可修改
    }
    getType()
    form.value.customerType = 1
  }

  const deductionOrderChange = (val, option) => {
    if (val) {
      const [prefix, content] = option.orderCode.split(/[()]/).filter(Boolean)
      form.value.orderNo = prefix
      form.value.availableAmount = content
      form.value.deductionOrderId = val
      form.value.orderCode = option.orderCode
      form.value.payType = option.payType
      form.value.deductionOrderType = option.orderType
    } else {
      form.value.orderNo = ''
      form.value.availableAmount = ''
      form.value.deductionOrderId = ''
      form.value.orderCode = ''
      form.value.payType = ''
      form.value.deductionOrderType = ''
    }
  }

  /**
   * 获取订单押金收取方式的统一处理函数
   */
  const getOrderDepositInfo = async (id, api) => {
    const res = await api({ id })
    return res.result
  }

  // 整理收付款方式
  const mapPayWay = (data) => {
    paywayEnum.value = data.map(({ way, wayStr, type }) => ({
      value: way,
      label: wayStr,
      type,
    }))
    console.log('mapPayWay ', paywayEnum.value)
  }

  /**
   * 处理押金抵扣过滤逻辑
   */
  const handleDepositFilter = (data, orderInfo) => {
    const { orderSource, violationDepositFee } = orderInfo
    const shouldFilter = orderSource == 1 && (!violationDepositFee || violationDepositFee.feeStatus == 1)
    const filteredData = shouldFilter ? data.filter((i) => i.way != '4') : data
    return deductionOrderList.value.length > 0 && deductionOrderList.value[0].payType == 2 ? filteredData : data.filter((i) => i.way != '4')
  }

  /**
   * 统一处理收付款方式过滤
   */
  const filterPayType = async (data) => {
    // 收款且有关联订单时需要特殊处理
    if (costType.value == 0 && orderId.value) {
      const api = orderType.value == 3 ? getDepositWay : getDepositType
      const orderInfo = await getOrderDepositInfo(orderId.value, api)
      const filteredData = await handleDepositFilter(data, orderInfo)
      mapPayWay(filteredData)
      return
    }

    // 其他情况直接过滤掉押金抵扣方式
    mapPayWay(data.filter((i) => i.way != '4'))
  }

  /**
   * 处理违章费用的支付方式
   */
  const handleViolationPayment = async (data, enterpriseDetail, shouldShowJialian, isOffline) => {
    // 过滤支付方式
    let paymentMethods = data.filter((i) => {
      if (feeNameId.value == 551) {
        return !['2', '3', '5'].includes(i.way)
      }
      return true
    })

    // 处理嘉联支付显示
    const shouldHideJialian = !enterpriseDetail.jialianEnabled || !shouldShowJialian || !isOffline
    if (shouldHideJialian) {
      paymentMethods = paymentMethods.filter((i) => i.way != '-1')
    }

    // 获取押金订单列表
    const depositOrders = await getDepositOrderList({
      memberId: violationdata.value[0].violation.memberId,
      orderId: orderId.value,
      orderType: orderType.value == 3 ? 0 : 1,
      payTypeList: [2, 4],
    })

    deductionOrderList.value = depositOrders.result || []

    // 根据订单数量处理支付方式
    if (!deductionOrderList.value.length) {
      await filterPayType(paymentMethods)
      return
    }

    if (deductionOrderList.value.length == 1) {
      const isZhima = deductionOrderList.value[0].payType == 4
      isZhima ? mapPayWay(paymentMethods) : await filterPayType(paymentMethods)
      return
    }

    mapPayWay(paymentMethods)
  }

  /**
   * 获取支付方式列表
   */
  const paywayEnum = ref([])
  const deductionOrderList = ref([])
  const getType = async () => {
    // 判断是否显示嘉联支付
    const shouldShowJialian = computed(() => {
      if (!violationdata.value.length) return false

      const isCollection = violationdata.value.every((item) => item.costType == 0)
      const hasPositiveAmount = form.value.actualAmount > 0

      if (violationdata.value.length == 1) {
        return isCollection && hasPositiveAmount
      }
      return (isCollection || !isCollection) && hasPositiveAmount
    })

    // 获取企业详情
    const enterpriseDetail = ref({})
    enterpriseDetail.value = await userInfoStore.setEpDetail(false)

    // 获取支付方式列表
    const { result: paymentData } = await getAccountByPageData({ type: costType.value })

    // 违章费用特殊处理
    if (feeCategory.value == 4) {
      const isOffline = violationdata.value.every((item) => item.feeType == 1)

      await handleViolationPayment(paymentData, enterpriseDetail.value, shouldShowJialian.value, isOffline)
      return
    }

    // 非违章费用处理
    const filteredData = paymentData
      .filter((i) => !['1', '2', '3', '4', '5'].includes(i.way))
      .map((item) => ({
        value: item.way,
        label: item.wayStr,
        type: item.type,
      }))

    paywayEnum.value = filteredData
  }

  // 获取账号
  const typeChange = (e) => {
    console.log('e', e)

    if (e == -1) {
      rules.value.account = {
        required: true,
        message: '请选择',
      }
    } else {
      form.value.account = ''
      delete rules.value.account
    }

    if (e == 4) {
      rules.value.deductionOrderId = {
        required: true,
        message: '请选择',
      }

      if (deductionOrderList.value.length > 0 && deductionOrderList.value[0].orderCode.includes('本单')) {
        deductionOrderChange(deductionOrderList.value[0].orderId, deductionOrderList.value[0])
      }
    } else {
      form.value.orderNo = ''
      form.value.availableAmount = ''
      form.value.deductionOrderId = ''
      form.value.orderCode = ''
      delete rules.value.deductionOrderId
    }

    paywayEnum.value.forEach((el) => {
      if (el.value == e) {
        getAccountByWayAndType({ way: Number(el.value), type: costType.value }).then((res) => {
          var children = res.result.map((childItem) => {
            return {
              value: childItem.id,
              label: form.value.paymentWay != -1 ? childItem.account + '_' + childItem.bank : childItem.bank,
            }
          })

          if (children.length == 1 && form.value.paymentWay == -1) {
            form.value.account = children[0].value
          }

          accountList.value = children
        })
      }
    })
  }
  // change
  const customerChange = (val, option) => {
    form.value.customerName = option.supplierName
    form.value.customerId = option.id
  }

  const toDeductionOrderDetail = () => {
    uni.navigateTo({
      url: `/pages/order/short-order/free-deposit-detail?orderId=${form.value.deductionOrderId}`,
    })
  }

  // 提交
  const toConfirm = () => {
    okLoading.value = true
    veFormRef.value.validate((valid, errors) => {
      if (valid) {
        console.log('验证成功', form.value)

        if (feeCategory.value == 4) {
          form_data.value = {
            idList: [feeRecordId.value],
            ...form.value,
          }

          violationConfirmFee(form_data.value)
            .then((res) => {
              okLoading.value = false
              if (res.code == 200) {
                if (form_data.value.paymentWay == -1) {
                  uni.navigateTo({
                    url: `/pages/common/components/qrcode?id=${res.result}&from=asset/asset-fee/confirm-fee`,
                  })
                } else {
                  useToast({
                    title: '确认成功',
                  }).then(() => {
                    // uni.$emit('refreshData')
                    uni.navigateBack()
                  })
                }
              }
            })
            .finally(() => {
              okLoading.value = false
            })
        } else {
          form_data.value = {
            idList: [feeRecordId.value],
            ...form.value,
          }
          confirmAssetFee(form_data.value)
            .then((res) => {
              okLoading.value = false
              if (res.code == 200) {
                useToast({
                  title: '确认成功',
                }).then(() => {
                  // uni.$emit('refreshData')
                  uni.navigateBack()
                })
              }
            })
            .finally(() => {
              okLoading.value = false
            })
        }
      } else {
        foldValidate(errors)
        okLoading.value = false
        console.log('验证失败', errors)
      }
    })
  }

  onLoad((options) => {
    console.log('options', options)

    feeRecordId.value = options.id
    feeCategory.value = options.feeCategory
    orderId.value = options.orderId
    orderType.value = options.orderType
    feeNameId.value = options.feeNameId
    rules.value.customerName.message = feeCategory.value == 4 ? '请输入' : '请选择'
    getDetail(feeRecordId.value)
  })
</script>

<style lang="scss" scoped>
  .container {
    height: auto;
    min-height: 100%;
    padding: 24rpx;
  }
  .viewports {
    background: #f7f8fa;
    display: flex;
    flex-direction: column;
    padding: 24rpx;
  }
  .status-1 {
    background: #ffece8;
    color: #ff7d00;
    border: 2rpx solid #ff7d00;
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
  .status-2 {
    background: #e8f7ff;
    color: #3491fa;
    border: 2rpx solid #3491fa;
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
  .status-4 {
    background: #f5e8ff;
    color: #722ed1;
    border: 2rpx solid #722ed1;
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
  .line {
    width: 100%;
    background: #d8d8d8;
    height: 1rpx;
  }

  .fee-item {
    overflow-x: scroll;
    margin-top: 24rpx;
    .fee-table {
      width: 800rpx;
      .tlt {
        width: 100%;
        height: 88rpx;
        background: #f7f8fa;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: #8491a8;
        font-size: 24rpx;
        view:nth-child(1) {
          width: 320rpx;
          margin-left: 24rpx;
        }
        view:nth-child(2) {
          width: 160rpx;
        }
        view:nth-child(3) {
          width: 320rpx;
        }
      }
      .fee-first {
        width: 100%;
        margin: 32rpx 0 16rpx;
        background: #ffffff;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: #191c27;
        font-size: 28rpx;
        view:nth-child(1) {
          width: 320rpx;
          margin-left: 24rpx;
        }
        view:nth-child(2) {
          width: 160rpx;
        }
        view:nth-child(3) {
          width: 320rpx;
        }
      }
      .fee-other {
        margin-left: 22rpx;
        .twice {
          width: calc(100% - 20rpx);
          background: #f7f8fa;
          padding: 0 24rpx 24rpx;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          color: #191c27;
          font-size: 28rpx;
          view {
            margin-top: 24rpx;
          }
          view:nth-child(1) {
            width: 296rpx;
            margin-left: 24rpx;
          }
          view:nth-child(2) {
            width: 160rpx;
          }
          view:nth-child(3) {
            width: 320rpx;
          }
        }
        .third {
          width: calc(100% - 20rpx);
          background: #f7f8fa;
          padding: 0 24rpx 24rpx;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          color: #191c27;
          font-size: 28rpx;
          view:nth-child(1) {
            width: 248rpx;
            margin-left: 48rpx;
          }
          view:nth-child(2) {
            width: 160rpx;
          }
          view:nth-child(3) {
            width: 320rpx;
          }
        }
      }
    }
  }
  .bottom-btns {
    width: 100%;
    display: flex;
    flex-direction: column;
    .amount {
      color: #1e1e1e;
      font-size: 32rpx;
      font-weight: 400;
      display: flex;
      justify-content: flex-start;
      align-items: flex-end;
      margin: 12rpx 0 36rpx;
      .amount-num {
        color: #fe615a;
        font-size: 48rpx;
        font-weight: 600;
        line-height: 1;
      }
      .amount-pic {
        color: #fe615a;
        font-size: 24rpx;
        font-weight: 400;
        margin-left: 8rpx;
      }
    }
    .line {
      width: 100%;
      background: #d8d8d8;
      height: 1rpx;
      margin-bottom: 32rpx;
      transform: scaleY(0.5);
    }
  }
  :deep(.ve_tooltip__popper) {
    width: 420rpx;
    line-height: 38rpx;
    white-space: normal;
  }

  .deduction-order-select {
    width: 100%;
    font-size: 30rpx;
    font-weight: 400;
    color: #191c27;
    line-height: 44rpx;
  }

  .deduction-order-select-amount {
    color: #3072f6;
  }
  .placeholder {
    color: #8491a8;
  }
</style>
